<?php

class MatchController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/column2';
    public $defaultAction='admin';



    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
			'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
        array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','list','createFromMobile','deleteFromMobile'),
				'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('@'),
        ),
        array('deny',  // deny all users
				'users'=>array('*'),
        ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
			'model'=>$this->loadModel($id),
        ));
    }

    public function actionDeletefromMobile($id=-1,$pass=""){
        $cr = new CDbCriteria();
        $cr->condition = "name = 'Pass'";
        $setting = Settings::model()->find($cr);
         
        header("Content-type: text/xml");
        $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        if($pass == $setting->value){
            if($id==-1){
                $xml_output.= "<create response=\"Λάθος αγώνας\" />";
            } else{
                $match = Match::model()->findByPk($id);
                if($match == null){
                    $xml_output.= "<create response=\"Λάθος αγώνας\" />";
                } else{
                    $match->deleted = 1;
                    if($match->save()){
                        $xml_output.= "<create response=\"Ο αγώνας διεγράφη\" />";
                    }else{
                        $xml_output.= "<create response=\"Κάποιο σφάλμα προέκυψε\" />";
                    }
                }
            }
        }else{
            $xml_output.= "<create response=\"Λάθος συνθηματικό\" />";
        }
        echo $xml_output;
    }

    public function actionCreateFromMobile($id=-1,$pass="",$time="",$tour=-1,$home="",$away="",$stad="",$chan=-1, $homeGoals=0, $awayGoals = 0){
        $cr = new CDbCriteria();
        $cr->condition = "name = 'Pass'";
        $setting = Settings::model()->find($cr);
         
        header("Content-type: text/xml");
        $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        if($pass == $setting->value){
            if($id==-1){
                $match = new Match();
            } else{
                $match = Match::model()->findByPk($id);
            }
            if($match == null){
                $xml_output.= "<create response=\"Λάθος αγώνας\" />";
            }else if($time == ""){
                $xml_output.= "<create response=\"Λάθος ημερομηνία\" />";
            }else if($tour ==-1 ){
                $xml_output.= "<create response=\"Λάθος διοργάνωση\" />";
            }else if($chan ==-1 ){
                $xml_output.= "<create response=\"Λάθος κανάλι\" />";
            }else if($home =="" ){
                $xml_output.= "<create response=\"Λάθος γηπεδούχος\" />";
            }else if($away =="" ){
                $xml_output.= "<create response=\"Λάθος φιλοξενούμενος\" />";
            }else{
                $match->datetime = $time;
                $match->tournament_id = $tour;
                $match->channel_id = $chan;
                $match->hometeam = $home;
                $match->awayteam = $away;
                $match->stadium = $stad;
                $match->homegoals = $homeGoals;
                $match->awaygoals = $awayGoals;
                if($match->save()){
                    if($id==-1){
                        $xml_output.= "<create response=\"Ο αγώνας δημιουργήθηκε\" />";
                    } else{
                        $xml_output.= "<create response=\"Ο αγώνας μετατράπηκε\" />";
                    }
                }else{
                    $xml_output.= "<create response=\"Κάποιο σφάλμα προέκυψε\" />";
                }
            }

        }else{
            $xml_output.= "<create response=\"Λάθος συνθηματικό\" />";
        }
        echo $xml_output;
    }

    public function actionList($updated = 0, $period = ""){
        $this->layout = null;
        $cr = new CDbCriteria();
        $cr->order = 'datetime DESC';
        $period == "" ? $seasonClause = "" : $seasonClause = " AND period =  '".$period."'";
        $cr->condition = 'updated > '.$updated.' '.$seasonClause;
        $matches = Match::model()->findAll($cr);
        $crV = new CDbCriteria();
        $crV->condition = "name = 'Version'";
        $setting = Settings::model()->find($crV);
        header("Content-type: text/xml");
        $xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        $xml_output .= "<matches version='".$setting->value."'>";
        foreach ($matches as $match){

            $xml_output .=	"<match>".
		"<id>". $match->_id."</id>".
		"<tournament>". $match->tournament."</tournament>".
		"<period>". $match->period."</period>".
		"<datetime>". $match->datetime."</datetime>".
		"<hometeam>". $match->hometeam."</hometeam>".
		"<awayteam>". $match->awayteam."</awayteam>".
		"<homegoals>". $match->homegoals."</homegoals>".
		"<awaygoals>". $match->awaygoals."</awaygoals>".
            "<players>";

            if(count($match->playersArray)>0){
                foreach ($match->playersArray as $player){
                    $xml_output .= "<player>". Match::$PLAYERS[$match->period][$player]."</player>";
                }
            }
            $xml_output .= "</players>";
            $xml_output .= "<stadium>". $match->stadium."</stadium>".
		"<channel>". $match->channel."</channel>".
		"<updated>". $match->updated."</updated>".
		"<deleted>". $match->deleted."</deleted>";
            $xml_output .="<details>";
            foreach ($match->details as $detail){
                $xml_output .= "<detail>".
			    "<id>".$detail->_id."</id>".
			    "<type>".$detail->type."</type>".
			    "<minute>".$detail->min."</minute>".
			    "<player>".$detail->player."</player>".
			    "<comment>".$detail->comment."</comment>".
			    "<side>".$detail->side."</side>".
			    "<deleted>".$detail->deleted."</deleted>".
			     "</detail>";
            }
            $xml_output .= "</details></match>";
             
        }
        $xml_output .="</matches>";
        echo $xml_output;
        //$this->renderPartial("list",array("matches"=>$matches));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Match;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Match']))
        {
            $model->attributes=$_POST['Match'];
            if($model->save())
            $this->redirect(array('view','id'=>$model->_id));
        }

        $this->render('create',array(
			'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Match']))
        {
            $model->attributes=$_POST['Match'];
            if($model->save())
            $this->redirect(array('view','id'=>$model->_id));
        }

        $this->render('update',array(
			'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
        throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Match');
        $this->render('index',array(
			'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new Match('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Match']))
        $model->attributes=$_GET['Match'];

        $this->render('admin',array(
					'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Match::model()->findByPk((int)$id);
        if($model===null)
        throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='match-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
